﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 玩家角色控制
/// </summary>
public class PlayerController : MonoBehaviour {

    public int z = 3;
    private int x = 2;

    private Color colorOne = new Color(154 / 255f, 111 / 255f, 235 / 255f);
    private Color colorTwo = new Color(160 / 255f, 120 / 255f, 230 / 255f);
    
    private Transform m_transform;

    private MapManager m_mapmanager;
    private CameraFollow m_camerafollow;
    private UIManager m_UIManager;

    public bool life = false;

    public int gemCount ;
    public int scorecount ;

    private void AddGemCount()
    {
        gemCount++;
        Debug.Log("宝石数为：" + gemCount);
    }

    private void AddScoreCount()
    {
        scorecount++;
        Debug.Log("总分为：" + scorecount);
    }

    private void SaveData()
    {
        PlayerPrefs.SetInt("GemCount",gemCount);
        if (scorecount > PlayerPrefs.GetInt("TopScore", 0))
        {
            PlayerPrefs.SetInt("TopScore", scorecount);
        }
    }

    void Start()
    {
        gemCount=PlayerPrefs.GetInt("GemCount", 0);        
        m_transform = gameObject.GetComponent<Transform>();

        m_mapmanager = GameObject.Find("MapManager").GetComponent<MapManager>();
        m_camerafollow = GameObject.Find("Main Camera").GetComponent<CameraFollow>();
        m_UIManager = GameObject.Find("UI Root").GetComponent<UIManager>();
    }

    public void StartGame()
    {
        SetPlayerPos();
        m_camerafollow.startfollow = true;
        m_mapmanager.StartFallDown();
        life = true;
    }

    void Update()
    {        
        if (Input.GetKeyDown(KeyCode.M))
        {
            StartGame();
        }
        if (life)
        {
            PlayerControl();            
        }
        CalcPosition();
    }

    public void Left()
    {
        if (x != 0)
        {
            z++;
            AddScoreCount();
        }
        if (z % 2 == 1 && x != 0)
        {
            x--;
        }
        SetPlayerPos();
    }

    public void Right()
    {
        if (x == 4 && z % 2 == 1)
        {

        }
        else
        {
            z++;
            AddScoreCount();
        }
        if (z % 2 == 0 && x != 4)
        {
            x++;
        }
        SetPlayerPos();
    }
	
    private void PlayerControl()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            Left();
        }
        if (Input.GetKeyDown(KeyCode.D))
        {
            Right();
        }
    }

    private void SetPlayerPos()
    {
        GameObject playerposgo = m_mapmanager.maplist[z][x];
        Transform playerpos = m_mapmanager.maplist[z][x].GetComponent<Transform>();

        m_transform.position = playerpos.position + Vector3.up * 0.132f;
        m_transform.rotation = playerpos.rotation;
        MeshRenderer trailrender = null;
        if (playerposgo.tag == "Tile")
        {            
            trailrender = playerpos.Find("normal_a2").gameObject.GetComponent<MeshRenderer>();            
        }
        else if (playerposgo.tag == "LandSpike")
        {
            trailrender = playerposgo.GetComponent<Transform>().Find("moving_spikes_a2").GetComponent<MeshRenderer>();            
        }
        else if (playerposgo.tag == "SkySpike")
        {
            trailrender = playerposgo.GetComponent<Transform>().Find("smashing_spikes_a2").GetComponent<MeshRenderer>();            
        }

        if (trailrender!=null)
        {
            if (z % 2 == 0)
            {
                trailrender.material.color = colorOne;
            }
            else
            {
                trailrender.material.color = colorTwo;
            }
        }else
        {
            gameObject.AddComponent<Rigidbody>();
            StartCoroutine("GameOver", true);
        }
    }

    /// <summary>
    /// 计算新地图位置
    /// </summary>
    private void CalcPosition()
    {
        if (m_mapmanager.maplist.Count - z < 18)
        {
            m_mapmanager.AddPR();
            float offsetz = m_mapmanager.maplist[m_mapmanager.maplist.Count - 1][0].GetComponent<Transform>().position.z + m_mapmanager.bottom_length * 0.5f;
            m_mapmanager.CreateMapItem(offsetz);
        }
    }	

    private void OnTriggerEnter(Collider coll)
    {        
        if (coll.gameObject.tag == "Spike_Attack")
        {
            StartCoroutine("GameOver",false);            
        }
        if (coll.gameObject.tag == "Gem")
        {
            AddGemCount();
            GameObject.Destroy(coll.GetComponent<Transform>().parent.gameObject);
        }
    }

    public IEnumerator GameOver(bool b)
    {
        if (b)
        {
            yield return new WaitForSeconds(0.5f);
        }

        if (life)
        {
            SaveData();
            Debug.Log("游戏结束");
            m_camerafollow.startfollow = false;
            life = false;
            StartCoroutine("ResetGame");       
            //todoUI相关的操作
        }           
    }

    private void ResetPlayer()
    {
        GameObject.Destroy(gameObject.GetComponent<Rigidbody>());

        x = 2;
        z = 3;

        scorecount = 0;
    }

    private IEnumerator ResetGame()
    {
        yield return new WaitForSeconds(2);
        ResetPlayer();
        m_mapmanager.ResetGameMap();
        m_camerafollow.ResetCamera();
        m_UIManager.ResetUI();
    }

    public void Pay()
    {
        gemCount -= 100;
        PlayerPrefs.SetInt("gem", gemCount);
        m_UIManager.UpdateData(scorecount, gemCount);
    }
}
